﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;

namespace AttachDB
{
    class Program
    {
        /*
         USE [master]
        GO
        EXEC master.dbo.sp_detach_db @dbname = N'AdventureWorks',
        @keepfulltextindexfile = N'true'
        GO
        ----Step 2 : Move Data files and Log files to new location

        –—Step 3 : Attach Database using following script
        USE [master]
        GO
        CREATE DATABASE [AdventureWorks] ON
        ( FILENAME = N’C:\Data\AdventureWorks_Data.mdf’ ),
        ( FILENAME = N’C:\Data\AdventureWorks_Log.ldf’ )
        FOR ATTACH
        GO
        IF EXISTS ( SELECT name
        FROM master.sys.databases sd
        WHERE name = N’AdventureWorks’
        AND SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() )
        EXEC [AdventureWorks].dbo.sp_changedbowner @loginame=N’sa’,
        @map=false
        GO
         */
        static void ExecuteNonQuery(string sql)
        {
            var conn = new SqlConnection("Data Source=localhost;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=12345");
            var cmd = new SqlCommand("", conn);
            var cmdtext = sql;
            conn.Open();
            cmd.CommandText = cmdtext;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                Console.WriteLine("Attach database failed!");
            }
            finally
            {
                conn.Close();
                Console.WriteLine("Attach database successfully!");
            }

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            DirectoryInfo dic = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            string projPath = dic.Parent.Parent.FullName;//?
            var detachSQL = "master.dbo.sp_detach_db @dbname = N'lutru_UBND98'";
            var createSQL =
                            "CREATE DATABASE [lutru_UBND98] ON " +
                            "( FILENAME = N'"+projPath+"\\lutru_UBND98_Data.MDF' ), "+
                            "( FILENAME = N'" + projPath + "\\lutru_UBND98_Log.LDF' ) " +
                            "FOR ATTACH "/*+
                            "GO " + 
                            "IF EXISTS ( SELECT name "+
                            "FROM master.sys.databases sd "+
                            "WHERE name = N'lutru_UBND98' " +
                            "AND SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) "+
                            "EXEC [lutru_UBND98].dbo.sp_changedbowner @loginame=N'sa', " +
                            "@map=false "+
                            "GO "*/;
            ExecuteNonQuery(detachSQL);
            ExecuteNonQuery(createSQL);
        }
    }
}
